from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

from rbac.models import RbacUser, Role, UserRole, Permission
from rbac.forms import UserModelForm


@csrf_exempt
def user_login(request):
    """用户登录"""
    if request.method == 'POST':
        email = request.POST['email']
        password = request.POST['password']
        try:
            user = RbacUser.objects.get(email=email)
            if user.check_password(password):
                login(request, user)
                # 将用户所有信息写入session
                request.session['user_id'] = user.id
                request.session['username'] = user.username
                request.session['email'] = user.email
                request.session['first_name'] = user.first_name
                request.session['last_name'] = user.last_name
                
                # 获取用户的所有角色
                user_roles = list(user.roles.filter(is_active=True).values_list('code', flat=True))
                request.session['roles'] = user_roles
                
                # 为兼容性保留旧的role字段，优先使用新角色系统
                if user_roles:
                    # 如果有角色，使用第一个角色作为主角色
                    if 'super_admin' in user_roles or 'admin' in user_roles:
                        request.session['role'] = 'admin'
                    else:
                        request.session['role'] = 'user'
                else:
                    request.session['role'] = 'user'
                
                # 重定向到下一页或默认欢迎页面
                next_url = request.GET.get('next')
                if not next_url:
                    next_url = reverse('rbac:welcome')
                return redirect(next_url)
            else:
                messages.error(request, '邮箱或密码错误')
        except RbacUser.DoesNotExist:
            messages.error(request, '邮箱或密码错误')
        return redirect('rbac:login')
    
    return render(request, 'rbac/login.html', {'register_url': reverse('rbac:register')})


def user_logout(request):
    """用户登出"""
    request.session.flush()  # 使用flush()来完全删除session
    return redirect('rbac:login')


def register(request):
    """用户注册"""
    if request.method == 'POST':
        form = UserModelForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])
            user.save()
            
            # 为新用户分配默认角色（普通用户）
            try:
                default_role = Role.objects.get(code='user')
                UserRole.objects.create(user=user, role=default_role)
            except Role.DoesNotExist:
                pass  # 如果默认角色不存在，跳过
            
            messages.success(request, '账户创建成功，请登录')
            return redirect('rbac:login')
        else:
            messages.error(request, '请更正以下错误。')
    else:
        form = UserModelForm()
    return render(request, 'rbac/register.html', {'form': form})


@login_required
def user_management(request):
    """用户管理"""
    # 首先检查用户是否有权限访问这个页面
    if not request.current_user or not has_user_permission(request.current_user['id'], 'user.list'):
        messages.error(request, '您没有权限访问此页面')
        return redirect('/rbac/')
    
    if request.method == 'POST':
        action = request.POST.get('action')
        
        if action == 'add':
            if not has_user_permission(request.current_user['id'], 'user.add'):
                messages.error(request, '您没有添加用户的权限')
                return redirect('rbac:user_management')
                
            form = UserModelForm(request.POST)
            if form.is_valid():
                user = form.save(commit=False)
                password = request.POST.get('password')
                if password:
                    user.set_password(password)
                user.save()
                
                # 处理角色分配
                role_ids = request.POST.getlist('roles')
                if role_ids:
                    roles = Role.objects.filter(id__in=role_ids, is_active=True)
                    for role in roles:
                        UserRole.objects.create(
                            user=user, 
                            role=role, 
                            assigned_by_id=request.current_user['id']
                        )
                
                messages.success(request, '用户添加成功')
            else:
                messages.error(request, '请更正以下错误')
                
        elif action == 'edit':
            if not has_user_permission(request.current_user['id'], 'user.edit'):
                messages.error(request, '您没有编辑用户的权限')
                return redirect('rbac:user_management')
                
            user_id = request.POST.get('user_id')
            try:
                user = RbacUser.objects.get(id=user_id)
                user.email = request.POST.get('email')
                user.username = request.POST.get('username')
                user.first_name = request.POST.get('first_name', '')
                user.last_name = request.POST.get('last_name', '')
                
                # 检查密码字段是否为空，不为空才更新密码
                password = request.POST.get('password')
                if password:
                    user.set_password(password)
                user.save()
                
                # 处理角色更新（只有有角色管理权限的用户才能修改）
                if has_user_permission(request.current_user['id'], 'user.manage_roles'):
                    role_ids = request.POST.getlist('roles')
                    # 清除现有角色
                    UserRole.objects.filter(user=user).delete()
                    # 添加新角色
                    if role_ids:
                        roles = Role.objects.filter(id__in=role_ids, is_active=True)
                        for role in roles:
                            UserRole.objects.create(
                                user=user, 
                                role=role, 
                                assigned_by_id=request.current_user['id']
                            )
                
                messages.success(request, '用户信息更新成功')
            except RbacUser.DoesNotExist:
                messages.error(request, '用户不存在')
            except Exception as e:
                messages.error(request, f'更新失败: {str(e)}')
                
        elif action == 'delete':
            if not has_user_permission(request.current_user['id'], 'user.delete'):
                messages.error(request, '您没有删除用户的权限')
                return redirect('rbac:user_management')
                
            user_id = request.POST.get('user_id')
            try:
                user = RbacUser.objects.get(id=user_id)
                # 不允许删除自己
                if user.id == request.current_user['id']:
                    messages.error(request, '不能删除自己的账户')
                else:
                    user.delete()
                    messages.success(request, '用户删除成功')
            except RbacUser.DoesNotExist:
                messages.error(request, '用户不存在')
        
        return redirect('rbac:user_management')

    # GET请求 - 显示用户列表
    users = RbacUser.objects.all().prefetch_related('roles')
    form = UserModelForm()
    active_roles = Role.objects.filter(is_active=True)
    
    # 为每个用户添加角色信息
    users_with_roles = []
    for user in users:
        user_roles = list(user.roles.filter(is_active=True))
        users_with_roles.append({
            'user': user,
            'roles': user_roles,
            'role_names': ', '.join([role.name for role in user_roles]) if user_roles else '无角色'
        })
    
    context = {
        'users_with_roles': users_with_roles,
        'form': form,
        'active_roles': active_roles,
        'current_user': request.current_user,
        'can_manage_roles': has_user_permission(request.current_user['id'], 'user.manage_roles'),
        'can_add_user': has_user_permission(request.current_user['id'], 'user.add'),
        'can_edit_user': has_user_permission(request.current_user['id'], 'user.edit'),
        'can_delete_user': has_user_permission(request.current_user['id'], 'user.delete'),
    }
    
    return render(request, 'rbac/user_management.html', context)


@login_required
def account_info(request):
    """账户信息"""
    if request.method == 'POST':
        # 处理账户信息更新
        user = RbacUser.objects.get(id=request.current_user['id'])
        user.first_name = request.POST.get('first_name', '')
        user.last_name = request.POST.get('last_name', '')
        
        # 检查密码更新
        new_password = request.POST.get('new_password')
        if new_password:
            old_password = request.POST.get('old_password')
            if user.check_password(old_password):
                user.set_password(new_password)
                messages.success(request, '密码更新成功')
            else:
                messages.error(request, '原密码错误')
                return redirect('rbac:account_info')
        
        user.save()
        
        # 更新session信息
        request.session['first_name'] = user.first_name
        request.session['last_name'] = user.last_name
        
        messages.success(request, '账户信息更新成功')
        return redirect('rbac:account_info')

    # 获取当前用户信息
    current_user = request.current_user
    user_info = {
        'username': current_user['username'],
        'email': current_user['email'],
        'first_name': current_user.get('first_name', ''),
        'last_name': current_user.get('last_name', ''),
    }

    return render(request, 'rbac/account_info.html', {'user_info': user_info, 'current_user': request.current_user})


def dashboard(request):
    """仪表板页面"""
    if not request.current_user or not request.current_user.get('id'):
        return redirect('rbac:login')
    
    # 导入模型（移动到函数顶部避免作用域问题）
    from rbac.models import PermissionManager
    
    # 检查是否是超级用户，如果是则自动初始化系统
    current_user_obj = RbacUser.objects.get(id=request.current_user['id'])
    if current_user_obj.is_superuser:
        # 初始化权限和角色数据（如果还没有）
        if not Permission.objects.exists():
            PermissionManager.init_all()
            messages.success(request, '系统数据初始化成功')
        
        # 给超级用户分配管理员角色（如果还没有）
        if not current_user_obj.roles.exists():
            try:
                admin_role = Role.objects.get(code='admin')
                UserRole.objects.create(user=current_user_obj, role=admin_role)
                # 更新 session
                user_roles = list(current_user_obj.roles.filter(is_active=True).values_list('code', flat=True))
                request.session['roles'] = user_roles
                request.session['role'] = 'admin'
                messages.success(request, '已为您分配管理员角色')
            except Role.DoesNotExist:
                pass
    
    # 获取用户统计信息
    total_users = RbacUser.objects.count()
    total_roles = Role.objects.count()
    active_roles = Role.objects.filter(is_active=True).count()
    total_permissions = Permission.objects.count()

    
    
    context = {
        'current_user': request.current_user,
        'total_users': total_users,
        'total_roles': total_roles,
        'active_roles': active_roles,
        'total_permissions': total_permissions,
        'is_superuser': current_user_obj.is_superuser,
    }
    
    return render(request, 'rbac/dashboard.html', context)


def has_user_permission(user_id, permission_code):
    """检查用户是否具有指定权限"""
    if not user_id:
        return False
    
    try:
        user = RbacUser.objects.get(id=user_id)
        return user.has_permission(permission_code)
    except RbacUser.DoesNotExist:
        return False